package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.MyPage;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.service.IYddLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/ydd_link")
public class YddLinkController {

    @Autowired
    private IYddLinkService iYddLinkService;

    /**
     * 查询单个 链接详情
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(@RequestParam("id") Long id){
        YddLink yddLink = iYddLinkService.getById(id);
        return ResultData.ok("",yddLink);
    }

    /**
     * 链接修改
     * @param yddLink
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddLink yddLink){
        iYddLinkService.updateById(yddLink);
        return ResultData.ok("","");
    }

    /**
     * 链接删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData delete(@RequestParam("id") long id){
        iYddLinkService.removeById(id);
        return ResultData.ok("","");
    }

    /**
     * 链接添加
     * @param yddLink
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddLink yddLink){
        iYddLinkService.save(yddLink);
        return ResultData.ok("","");
    }

    /**
     * 链接列表
     * @param type
     * @param page1
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(@RequestParam("type") String type, @RequestParam("page") String page1, @RequestParam("limit") String limit){
        //当前页码数
        int page = Integer.parseInt(page1);
        //每页显示条数
        int pageSize = Integer.parseInt(limit);
        //添加查询条件  按分类type查找
        Page<YddLink> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<YddLink> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddLink::getType,type);
        iYddLinkService.page(pageInfo,lqw);
        //数据
        List<YddLink> yddLinkList = pageInfo.getRecords();
        //总条数
        long count = yddLinkList.size();
        //总页数
        long totalPage = count % pageSize == 0 ? count/pageSize : count/pageSize + 1;
        //返回自定义分页类
        MyPage myPage = new MyPage(count,totalPage,(long)pageSize,(long)page,yddLinkList);
        return ResultData.ok("",myPage);
    }
}
